package storage.multibuffer;

import static storage.sql.Types.INTEGER;

import java.util.ArrayList;
import java.util.List;

import compiler.absyn.Constant;
import compiler.absyn.IntConstant;
import compiler.absyn.StringConstant;
import engine.query.Scan;

import storage.file.Block;
import storage.record.RecordPage;
import storage.record.Schema;
import storage.record.TableInfo;
import storage.tx.Transaction;

public class ChunkScan implements Scan{
	
	private List<RecordPage> pages = new ArrayList<RecordPage>();
	private int startbnum;
	private int endbnum;
	private int current;
	private Schema sch;
	private RecordPage rp;

	public ChunkScan(TableInfo ti, int startbnum, int endbnum, Transaction tx) {
		this.startbnum = startbnum;
		this.endbnum = endbnum;
		this.sch = ti.schema();
		String filename = ti.fileName();
		for(int i = startbnum; i <= endbnum; i++) {
			Block blk = new Block(filename, i);
			pages.add(new RecordPage(blk, ti, tx));
		}
		beforeFirst();
	}
	
	@Override
	public void beforeFirst() {
		// TODO Auto-generated method stub
		moveToBlock(startbnum);
		
	}

	private void moveToBlock(int startbnum2) {
		// TODO Auto-generated method stub
		current = startbnum2;
		rp = pages.get(current - startbnum);
		rp.moveToID(-1);
	}

	@Override
	public void close() {
		// TODO Auto-generated method stub
		for(RecordPage r : pages) {
			r.close();
		}
	}

	@Override
	public int getInt(String fldname){
		// TODO Auto-generated method stub
		return rp.getInt(fldname);
	}

	@Override
	public String getString(String fldname) {
		// TODO Auto-generated method stub
		return rp.getString(fldname);
	}

	@Override
	public Constant getVal(String fldname){
		// TODO Auto-generated method stub
		if(sch.type(fldname) == INTEGER) {
			return new IntConstant(rp.getInt(fldname));
		} else {
			return new StringConstant(rp.getString(fldname));
		}
	}

	@Override
	public boolean hasField(String fldname) {
		// TODO Auto-generated method stub
		return sch.hasField(fldname);
	}

	@Override
	public boolean next()  {
		// TODO Auto-generated method stub
		while(true) {
			if(rp.next()) {
				return true;
			}
			if(current == endbnum) {
				return false;
			}
			moveToBlock(current + 1);
		}
	}
}
